/**
 * @Description:
 * @Author HP
 * @create 2021/8/20 9:49
 */
import { make } from 'vuex-pathify'
import api from '@/api/'
import defaultSetting from '@/setting'

const { user } = JSON.parse(localStorage.getItem(defaultSetting.localstorageEntry.systemInfo)) || {}

const state = {
  timestamp: '时间戳',
  info: {}, // 用户信息
  appPermissions: [],
  commPermissions: [],
  tokenType: 'bearer', // token_type
  accessToken: user?.accessToken, // token
  refreshToken: user?.refreshToken // 暂时没用到，保留
}

const mutations = {
  ...make.mutations(state)
}

// timestamp(state, data) {
// s }

const actions = {
  /**
   * 跳转第三方统一登录页
   */
  loginToThirdParty() {
    window.location.href = `${window.$config.login_url}/auth/oauth/authorize?client_id=${window.$config.client_id}&redirect_uri=http://${window.location.host}/authorization&response_type=${window.$config.login_res_type}`
  },

  /**
   * 退出登录跳转第三方统一登录页
   */
  logoutToThirdParty() {
    window.location.href = `${window.$config.login_url}/auth/logout?client_id=${window.$config.client_id}&redirect_uri=http://${window.location.host}/authorization&response_type=${window.$config.login_res_type}`
  },

  /**
   * 获取token
   * @returns {Promise<boolean>}
   */
  async getAccessToken({ commit }, code = '') {
    const sendData = {
      params: {
        grant_type: 'authorization_code',
        code: code,
        redirect_uri: `http://${window.location.host}/authorization`
      }
    }
    const res = await api.authLoginByCode(sendData)
    commit('refreshToken', res.refresh_token)
    commit('accessToken', res.access_token)
  },

  /**
   * 获取用户信息
   */
  async getUserInfo({ commit }) {
    const res = await api.authGetUserInfo()
    console.log('获取用户信息', res)
    if (res.code == 200) {
      const { sysUser, commPermissions, appPermissions } = res.data
      commit('info', sysUser)
      commit('commPermissions', commPermissions)
      commit('appPermissions', appPermissions)
    }
    return res.data
  },

  /**
   * 退出登录
   */
  async loginOut({ state, commit, dispatch, context }) {
    // 这里要调用退出登录接口
    try {
      // if (state.accessToken) await api.authTokenLogout({ data: null })
    } finally {
      commit('info', {})
      commit('accessToken', null)
      commit('refreshToken', null)
      // removeCookies('SESSION') // 清除SESSION
      dispatch('app/loginOut', null, { root: true })
    }
  },

  /**
   * 清除缓存
   * @param commit
   */
  async clearCache({ commit }) {}
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
